import 'package:flutter/material.dart';
import 'package:flutter/services.dart';


class Scene07CursorMove extends StatefulWidget {
  const Scene07CursorMove({super.key});
  @override
  State<Scene07CursorMove> createState() => _Scene07CursorMoveState();
}

class _Scene07CursorMoveState extends State<Scene07CursorMove>
    implements DeltaTextInputClient {
  late final TextInputConnection _conn;
  TextEditingValue _value =
  const TextEditingValue(text: 'Flutter', selection: TextSelection.collapsed(offset: 7));
  final List<String> _logs = [];

  /* === DeltaTextInputClient === */
  @override
  TextEditingValue get currentTextEditingValue => _value;

  @override
  void updateEditingValueWithDeltas(List<TextEditingDelta> deltas) {
    for (final d in deltas) {
      if (d is TextEditingDeltaNonTextUpdate) {
        _logs.add('光标移动 → ${d.selection}');
      }
    }
    setState(() {
      for (final d in deltas) _value = d.apply(_value);
    });
  }

  /* 其余空实现，保证零报错 */
  @override
  void updateEditingValue(TextEditingValue value) {
    _logs.add('updateEditingValue');

  }
  @override
  void performAction(TextInputAction action) {
    _logs.add('performAction');

  }
  @override
  void connectionClosed() {
    _logs.add('connectionClosed');
  }

  @override
  void insertContent(KeyboardInsertedContent content) {
    _logs.add('insertContent');
  }
  @override
  void insertTextPlaceholder(Size size) {
    _logs.add('insertTextPlaceholder');
  }
  @override
  void performPrivateCommand(String action, Map<String, dynamic> data) {
    _logs.add('performPrivateCommand');
  }
  @override
  void performSelector(String selectorName) {
    _logs.add('performSelector');
  }
  @override
  void removeTextPlaceholder() {
    _logs.add('removeTextPlaceholder');
  }
  @override
  void showAutocorrectionPromptRect(int start, int end) {
    _logs.add('showAutocorrectionPromptRect');
  }
  @override
  void showToolbar() {
    _logs.add('showToolbar');
  }
  @override
  void updateFloatingCursor(RawFloatingCursorPoint point) {
    _logs.add('updateFloatingCursor');
  }

  /* === 生命周期 === */
  @override
  void initState() {
    super.initState();
    _conn = TextInput.attach(
      this,
      const TextInputConfiguration(enableDeltaModel: true),
    )
      ..show()
      ..setEditingState(_value);
  }

  @override
  void dispose() {
    _conn.close();
    super.dispose();
  }

  /* === 手动触发光标移动 === */
  void _moveCursor(int position) {
    final delta = TextEditingDeltaNonTextUpdate(
      oldText: _value.text,
      selection: TextSelection.collapsed(offset: position),
      composing: TextRange.empty,
    );
    updateEditingValueWithDeltas([delta]);
  }

  /* === UI === */
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('光标移动 Delta 场景')),
      body: Column(
        children: [
          Expanded(
            child: ListView.builder(
              padding: const EdgeInsets.all(8),
              itemCount: _logs.length,
              itemBuilder: (_, i) => Text(_logs[i],
                  style: const TextStyle(fontSize: 12, fontFamily: 'monospace')),
            ),
          ),
          Padding(
            padding: const EdgeInsets.all(12),
            child: TextField(
              controller: TextEditingController.fromValue(_value),
              decoration: const InputDecoration(
                hintText: '光标位置演示',
                border: OutlineInputBorder(),
              ),
              onChanged: (_) {},
            ),
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              ElevatedButton(
                onPressed: () => _moveCursor(0),
                child: const Text('移到 0'),
              ),
              ElevatedButton(
                onPressed: () => _moveCursor(4),
                child: const Text('移到 4'),
              ),
              ElevatedButton(
                onPressed: () => _moveCursor(7),
                child: const Text('移到 7'),
              ),
            ],
          ),
        ],
      ),
    );
  }

  @override
  // TODO: implement currentAutofillScope
  AutofillScope? get currentAutofillScope => throw UnimplementedError();

  @override
  void didChangeInputControl(TextInputControl? oldControl, TextInputControl? newControl) {
    // TODO: implement didChangeInputControl
  }
}